package md.NJavaOppo;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.widget.Toast;
import com.heytap.msp.mobad.api.MobAdManager;
import com.nearme.game.sdk.GameCenterSDK;
import com.nearme.game.sdk.callback.ApiCallback;
import com.nearme.game.sdk.callback.GameExitCallback;
import com.nearme.game.sdk.callback.SinglePayCallback;
import com.nearme.game.sdk.common.model.ApiResult;
import com.nearme.game.sdk.common.model.biz.PayInfo;
import com.nearme.game.sdk.common.util.AppUtil;
import com.nearme.platform.opensdk.pay.PayResponse;
import java.util.Random;

import md.NJavaBase.ICallbackQWEvent;
import md.NJavaBase.NJavaBase;
import md.NJavaBase.QWEvent;
import md.NJavaBase.QWEventDispatcher;

/*
【manifests修改】

<!--闪屏广告必须全屏展示，通过android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen"设置你的SplashActivity为全屏显示，
闪屏只支持竖屏展示，通过android:screenOrientation="portrait" 设置你的SplashActivity为竖屏显示-->
<activity
    android:name="md.NJavaOppo.OppoSplashActivity"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

【配置资源路径】

在资源搜寻路径中加入 'src/md/NJavaOppo/res'

sourceSets.main {
    ...
    res.srcDirs "../res", 'res','src/md/NJavaOppo/res'
    ...
}
*/

public class NJavaOppo {
    static String Tag="NJavaOppo";

    //防沉迷结果返回
    //结果码含义
    //-1实名认证失败，但还可以继续玩游戏
    //-2实名认证失败，不允许继续游戏，CP需自己处理退出游戏
    //>=0代表用户的年龄
    //      age<18已实名但未成年，CP开始处理防沉迷
    //      age>=18已实名且已成年，尽情玩游戏吧
    public static final String EVT_VERIFIED_RESULT = "EVT_VERIFIED_RESULT";

    //登录结果 0成功 其它失败
    public static final String EVT_LOGIN_RESULT = "EVT_LOGIN_RESULT";

    public static void go()
    {
        Log.d(Tag,"NJavaOppo init begin");
        Activity activity = NJavaBase.getActivity();

        String appSecret = "";
        try {
            ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(
                    activity.getPackageName(), PackageManager.GET_META_DATA
            );

            appSecret = appInfo.metaData.getString("OPPO_GAMECENTER_APPSECRET")  ;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(Tag, "NJavaOppo.Go error!");
            e.printStackTrace();
        }
        GameCenterSDK.init(appSecret, activity);

        Log.d(Tag,"NJavaOppo init end");



        //初始化oppo广告系统
        OppoAd.go();
    }

    public static void Pay()
    {
        final Activity activity = NJavaBase.getActivity();
        PayInfo payInfo = createTestPayInfo(1);
        GameCenterSDK.getInstance().doSinglePay(
                activity, payInfo,
                new SinglePayCallback() {
            // add OPPO 支付成功处理逻辑~
                    public void onSuccess(String resultMsg) {
                        Toast.makeText(activity, "支付成功",Toast.LENGTH_SHORT).show();
                    }
                    // add OPPO 支付失败处理逻辑~
                    public void onFailure(String resultMsg, int resultCode) {
                        if (PayResponse.CODE_CANCEL != resultCode) {
                            Toast.makeText(activity, "支付失败",Toast.LENGTH_SHORT).show();
                        }
                        else {
                            // 取消支付处理
                            Toast.makeText(activity, "支付取消",Toast.LENGTH_SHORT).show();
                        }
                    }
                    /* bySelectSMSPay 为true表示回调来自于支付渠道列表选择短信支付，false表示没有 网络等非主动选择短信支付时候的回调 */
                    public void onCallCarrierPay(PayInfo payInfo, boolean bySelectSMSPay) {
                        // add 运营商支付逻辑~
                        Toast.makeText(activity, "运营商支付",Toast.LENGTH_SHORT).show();
                    }
        });

    }

    //amount消费总金额
    private static PayInfo createTestPayInfo(int amount){
        PayInfo payInfo = new PayInfo(
                System.currentTimeMillis() + new Random().nextInt(1000) + "",//订单号
                "自定义字段",
                amount//消费总金额
        );
        //payInfo.setProductDesc("商品描述");
        payInfo.setProductName("300符石");
        // payInfo.setShowCpSmsChannel(true);//sdk支付界面是否显示运营商短信入口，true显示， false不显示
        // payInfo.setUseCachedChannel(true);//设置是否使用上次使用过的支付方式
        // 支付结果服务器回调地址，不通过服务端回调发货的游戏可以不用填写~
        // payInfo.setCallbackUrl( "http://gamecenter.wanyol.com:8080/gamecenter/callback_test_url");
        return payInfo;
    }


    //执行登录游戏逻辑
    public  static void login()
    {
        GameCenterSDK.getInstance().doLogin(NJavaBase.getActivity(), new ApiCallback() {
            @Override
            public void onSuccess(String resultMsg) {
                // 登录成功
                if(resultMsg!=null)
                    Log.e(Tag,String.format("登录成功 msg:%s",resultMsg));

                QWEvent evt = new QWEvent(EVT_LOGIN_RESULT,new Integer(0));
                g_Events.dispatchEvent(evt);
            }
            @Override
            public void onFailure(String resultMsg, int resultCode) {

                if(resultMsg!=null)
                    Log.e(Tag,String.format("登录失败 msg:%s code:%d",resultMsg,resultCode));

                // 登录失败
                QWEvent evt = new QWEvent(EVT_LOGIN_RESULT,new Integer(99));
                g_Events.dispatchEvent(evt);
            }
        });
    }

    //退出游戏
    public static void exitGame()
    {
        GameCenterSDK.getInstance().onExit(NJavaBase.getActivity(),new GameExitCallback() {
            @Override
            public void exitGame()
            {
                MobAdManager.getInstance().exit(NJavaBase.getActivity());//释放广告资源

                //退出进程
                AppUtil.exitGameProcess(NJavaBase.getActivity());
            }
        });
    }

    //获取防沉迷信息
    public static void getVerifiedInfo()
    {
        GameCenterSDK.getInstance().doGetVerifiedInfo(new ApiCallback() {
            @Override
            public void onSuccess(String resultMsg) {
                try {
                    //解析年龄（age）
                    int age = Integer.parseInt(resultMsg);
                    /*
                    if (age < 18) {
                        //已实名但未成年，CP开始处理防沉迷
                    } else {
                        //已实名且已成年，尽情玩游戏吧
                    }*/
                    QWEvent evt = new QWEvent(EVT_VERIFIED_RESULT,new Integer(age));
                    g_Events.dispatchEvent(evt);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(String resultMsg, int resultCode) {
                if(resultCode == ApiResult.RESULT_CODE_VERIFIED_FAILED_AND_RESUME_GAME){
                    //实名认证失败，但还可以继续玩游戏
                    QWEvent evt = new QWEvent(EVT_VERIFIED_RESULT,new Integer(-1));
                    g_Events.dispatchEvent(evt);
                }else if(resultCode == ApiResult.RESULT_CODE_VERIFIED_FAILED_AND_STOP_GAME){
                    //实名认证失败，不允许继续游戏，CP需自己处理退出游戏
                    QWEvent evt = new QWEvent(EVT_VERIFIED_RESULT,new Integer(-2));
                    g_Events.dispatchEvent(evt);
                }
            }
        });
    }

    //跳转超休闲专区
    public static void jumpLeisureSubject() {
        GameCenterSDK.getInstance().jumpLeisureSubject();
    }

    //监听事件
    public static void addEventListener(String type, ICallbackQWEvent listener)
    {
        g_Events.addEventListener(type,listener);
    }

    //移除监听
    public static void  removeEventListener(String type,ICallbackQWEvent listener)
    {
        g_Events.removeEventListener(type,listener);
    }

    static QWEventDispatcher g_Events = new QWEventDispatcher();
}